package cn.lw.utils;

import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class AccessUtil {

    public static <T> List Con2(String filePath, String sql, AccessOper<T> accessOper) {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;
        List<T> list = new ArrayList<>();
        try {
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
            con = DriverManager.getConnection("jdbc:ucanaccess://" + filePath);
            st = con.createStatement();
            DatabaseMetaData dbmd = con.getMetaData();
            ResultSet rstable = dbmd.getTables(null, null, "%", null);
            while (rstable.next()) {
                rs = st.executeQuery(sql);
                while (rs.next()) {
                    T bean = accessOper.BeanMapping(rs);
                    list.add(bean);
                }

            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (st != null) {
                try {
                    st.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        log.info("结果集【{}】",list);
        return list;
    }

    @FunctionalInterface
    public interface AccessOper<M>{
        M BeanMapping(ResultSet rs);
    }


}
